//复制文本
import useClipboard from 'vue-clipboard3'
import { ElMessage } from 'element-plus'

// i18n language  match title
import { i18n } from '@/lang'
// the keys using  zh file
import langEn from '@/lang/zh'
import settings from '@/settings'

// blob 下载
export const downloadFile = (name: string, blob: Blob) => {
  const a = document.createElement('a')
  a.download = name
  a.href = URL.createObjectURL(blob)
  document.body.appendChild(a)
  a.click()
  URL.revokeObjectURL(a.href)
  document.body.removeChild(a)
}
// url 下载
export const downloadTemplate = async (name: string, fileUrl: string) => {
  const link = document.createElement('a')
  link.href = fileUrl
  link.download = name
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 睡眠
export const sleepTimeout = (time: number) => {
  return new Promise((resolve) => {
    const timer = setTimeout(() => {
      clearTimeout(timer)
      resolve(null)
    }, time)
  })
}

//深拷贝
export function cloneDeep(obj, visited = new WeakMap()) {
  // 检查是否已经拷贝过该对象，避免循环引用
  if (visited.has(obj)) {
    return visited.get(obj)
  }

  // 非对象和函数直接返回
  if (typeof obj !== 'object' || obj === null) {
    return obj
  }

  // 创建拷贝对象
  let copy
  if (Array.isArray(obj)) {
    copy = []
    visited.set(obj, copy)
    for (let i = 0; i < obj.length; i++) {
      copy[i] = cloneDeep(obj[i], visited)
    }
  } else if (obj instanceof Set) {
    copy = new Set()
    visited.set(obj, copy)
    obj.forEach((value) => {
      copy.add(cloneDeep(value, visited))
    })
  } else if (obj instanceof Map) {
    copy = new Map()
    visited.set(obj, copy)
    obj.forEach((value, key) => {
      copy.set(key, cloneDeep(value, visited))
    })
  } else {
    copy = Object.create(Object.getPrototypeOf(obj))
    visited.set(obj, copy)
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        copy[key] = cloneDeep(obj[key], visited)
      }
    }
  }

  return copy
}
//copyValueToClipboard
const { toClipboard } = useClipboard()
export const copyValueToClipboard = (value: any) => {
  toClipboard(value)
  ElMessage.success('复制成功')
}
const { t, te } = i18n.global
export const langTitle = (title) => {
  if (!title) {
    return settings.title
  }
  for (const key of Object.keys(langEn)) {
    if (te(`${key}.${title}`) && t(`${key}.${title}`)) {
      return t(`${key}.${title}`)
    }
  }
  return title
}

//get i18n instance
export const getLangInstance = () => {
  return i18n.global as ObjKeys
}
